package com.example.quartz.demo;

import com.example.quartz.demo.job.HelloJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QuartzManagerService {

    @Autowired
    private Scheduler scheduler;


    /**
     * 添加Job
     * @param jobClass 任务类
     * @param jobName  任务名
     * @param jobGroupName 任务组
     * @param triggerName 事务名
     * @param cron 执行cron
     */
    public void  addJob(Class jobClass,String jobName,String jobGroupName,String triggerName,String cron) throws  Exception
    {
        JobDetail jobDetail = JobBuilder.newJob(jobClass)
                // 任务执行类
                .withIdentity(jobName, jobGroupName)
                // 任务名，任务组
                .build();
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, jobGroupName).startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
        // 4、调度执行  如果任务未启动
        if(!scheduler.isStarted())
        {
            scheduler.start();
        }
        scheduler.scheduleJob(jobDetail, trigger);// 设置调度相关的Job
    }

}
